package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private boolean firstInputFlag = true;
    private String defaultChar = "0";
    private Float cacheTextView;
    private String cacheSymbol;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onclickDo(View view){
        String val = ((Button)view).getText().toString();
        this.inputNum(val);
    }

    public void inputNum(String num){

        if(this.checkInput(num)) {
            TextView textView = this.getTextView();
            String origin = textView.getText().toString();
            if (this.firstInputFlag) {
                origin = num;
                this.firstInputFlag = false;
            } else {
                origin = origin + num;
            }
            Log.v(origin, "onclick");
            textView.setText(origin);
        }
    }

    public boolean checkInput(String str){

        String text = this.getTextView().getText().toString();
        switch (str){
            case "." : return text.indexOf(".") > 0 ? false : true;
        }
        return true;
    }

    public void inputSymbol(View view){
        String symbol = ((Button)view).getText().toString();
        this.cacheSymbol = symbol;
        this.firstInputFlag = true;
        this.cacheTextView = Float.parseFloat(this.getTextView().getText().toString());
        this.refreshTextView();
    }

    public void getResult(View view){
        TextView textView = this.getTextView();

        Float num1= this.cacheTextView;
        Float num2 = Float.parseFloat(textView.getText().toString());
        Float result;
        switch (this.cacheSymbol){
            case "+" : result = num1 + num2; break;
            case "-" : result = num1 - num2; break;
            default: result = num2;
        }

        textView.setText(result.toString());
        this.firstInputFlag = true;
    }

    public void refreshTextView(){
        TextView textView = this.getTextView();
        textView.setText(this.defaultChar);
    }

    public TextView getTextView(){
        return  (TextView)this.findViewById(R.id.textView);
    }
}
